
(function () {
  //变量声明
  var mouseFrom = {},
    mouseTo = {},
    drawType = null,
    canvasObjectIndex = 0,
    textbox = null
  var drawWidth = 2 //笔触宽度
  var color = "#000" //画笔颜色
  var drawingObject = null //当前绘制对象
  var moveCount = 1 //绘制移动计数器
  var doDrawing = false // 绘制状态
  var fabricHistoryJson = []
  var mods = 0
  var replayllist = []

  //初始化画板
  var canvas = new fabric.Canvas("c", {
    isDrawingMode: true,
    //开始就选中
    // skipTargetFind: true,
    // selectable: false,
    // selection: true

  })
  var canvas1 = new fabric.Canvas("re", {})
  window.canvas = canvas
  window.zoom = window.zoom ? window.zoom : 1
  canvas.freeDrawingBrush.color = color //设置自由绘颜色
  canvas.freeDrawingBrush.width = drawWidth

  //绑定画板事件
  canvas.on("mouse:down", function (options) {
    if (!options.pointer.x) {
      var xy = transformMouse(options.e.offsetX, options.e.offsetY)
    } else {
      var xy = transformMouse(options.pointer.x, options.pointer.y)
    }
    mouseFrom.x = xy.x
    mouseFrom.y = xy.y
    doDrawing = true
    // if (type == "remove") {
    //   var el = canvas.getActiveObject(); // 获取当前选择的元素
    //   canvas.remove(el);

    // }
  })
  canvas.on("mouse:up", function (options) {
    if (!options.pointer.x) {
      var xy = transformMouse(options.e.offsetX, options.e.offsetY)
    } else {
      var xy = transformMouse(options.pointer.x, options.pointer.y)
    }
    mouseTo.x = xy.x
    mouseTo.y = xy.y
    socket.emit("startConnect1", canvas.toJSON())
    drawingObject = null
    moveCount = 1
    doDrawing = false
    updateModifications(true)
  })
  canvas.on("mouse:move", function (options) {
    if (moveCount % 2 && !doDrawing) {
      //减少绘制频率
      return
    }
    moveCount++
    if (!options.pointer.x) {
      var xy = transformMouse(options.e.offsetX, options.e.offsetY)
    } else {
      var xy = transformMouse(options.pointer.x, options.pointer.y)
    }
    mouseTo.x = xy.x
    mouseTo.y = xy.y
    var dataTo = {
      drawType: drawType,
      mouseFromX: mouseFrom.x,
      mouseFromY: mouseFrom.y,
      mouseToX: mouseTo.x,
      mouseToY: mouseTo.y,
    }
    // socket.emit("startConnect", dataTo)
    drawing()
    socket.emit("startConnect1", canvas.toJSON())
  })

  // 接受画板数据
  socket.on("drawCanvas1", function (data) {
    replayllist.push(data)
    canvas.loadFromJSON(data)
  })
  //坐标转换
  function transformMouse(mouseX, mouseY) {
    return { x: mouseX / window.zoom, y: mouseY / window.zoom }
  }

  //绑定工具事件
  jQuery("#toolsul")
    .find("li")
    .on("click", function () {
      //设置样式
      jQuery("#toolsul").find("li>i") &&
        jQuery("#toolsul")
          .find("li>i")
          .each(function () {
            jQuery(this).attr("class", jQuery(this).attr("data-default"))
          })
      jQuery(this).addClass("active").siblings().removeClass("active")
      jQuery(this).find("i") &&
        jQuery(this)
          .find("i")
          .attr(
            "class",
            jQuery(this).find("i").attr("class").replace("black", "select")
          )
      drawType = jQuery(this).attr("data-type")
      console.log(drawType, "0000000000000000");
      canvas.isDrawingMode = false
      if (textbox) {
        // 退出文本编辑状态
        textbox.exitEditing()
        textbox = null
      }
      if (drawType == "rubber") {
        console.log("rubber")
        canvas.isDrawingMode = true
        canvas.freeDrawingBrush.color = "#fff" //设置自由绘颜色
        canvas.freeDrawingBrush.width = 50

      }
      if (drawType == "next") {
        redo()
        socket.emit("startConnect1", canvas.toJSON())
      }
      if (drawType == "back") {
        undo()
        socket.emit("startConnect1", canvas.toJSON())
      }
      if (drawType == "clear") {
        canvas.clear()
        socket.emit("startConnect1", canvas.toJSON())
      }
      if (drawType == "remove") {
        canvas.skipTargetFind = false; // canvas元素可选取
        var el = canvas.getActiveObject(); // 获取当前选择的元素
        if (!el._objects) {
          canvas.remove(el);
        } else {
          canvas.remove(el);
          el._objects.forEach(item => canvas.remove(item))

        }
      } else if (drawType == "drag") {
        canvas.selection = true
        canvas.skipTargetFind = false
        canvas.selectable = true
      } else {
        canvas.skipTargetFind = true //画板元素不能被选中
        canvas.selection = false //画板不显示选中
      }
    })
  var index = 0
  var timer = null

  //绘画方法
  function drawing() {
    if (drawingObject) {
      canvas.remove(drawingObject)
    }
    var canvasObject = null
    console.log(drawType, "被点击了");
    switch (drawType) {
      case "li":
        canvas.isDrawingMode = false
        break
      case "pen":
        canvas.isDrawingMode = true
        canvas.freeDrawingBrush.color = "#000" //设置自由绘颜色
        canvas.freeDrawingBrush.width = 2
        break
      case "arrow": //箭头
        canvasObject = new fabric.Path(
          drawArrow(mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y, 30, 30),
          {
            stroke: color,
            fill: "rgba(255,255,255,0)",
            strokeWidth: drawWidth,
          },
        )
        break
      case "line": //直线
        //mouseFrom.x mouseTo.x角度 mouseFrom.y mouseTo.y长度
        canvasObject = new fabric.Line(
          [mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y],
          {
            stroke: color,
            strokeWidth: drawWidth,
          }
        )
        break
      case "line1": //直线
        //mouseFrom.x mouseTo.x角度 mouseFrom.y mouseTo.y长度
        canvasObject = new fabric.Line(
          [mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y],
          {
            stroke: color,
            strokeWidth: 8,
          }
        )
        break
      case "dottedline": //虚线
        canvasObject = new fabric.Line(
          [mouseFrom.x, mouseFrom.y, mouseTo.x, mouseTo.y],
          {
            strokeDashArray: [5, 15],
            stroke: color,
            strokeWidth: drawWidth,
          }
        )
        break
      case "circle": //正圆
        var left = mouseFrom.x,
          top = mouseFrom.y
        var radius =
          Math.sqrt(
            (mouseTo.x - left) * (mouseTo.x - left) +
            (mouseTo.y - top) * (mouseTo.y - top)
          ) / 2
        canvasObject = new fabric.Circle({
          left: left,
          top: top,
          width: mouseTo.x,
          height: mouseTo.y,
          stroke: color,
          fill: "rgba(255, 255, 255, 0)",
          radius: radius,
          strokeWidth: drawWidth,
        })
        break
      case "louti": //楼梯
        var left = mouseFrom.x,
          top = mouseFrom.y
        const recta = new fabric.Rect({
          top: 0, //距离画布上边的距离
          left: 100, //距离画布左侧的距离，单位是像素
          width: 50, //矩形的宽度
          height: 60, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
          // objectCaching: false,
        })

        const rect1a = new fabric.Rect({
          top: 0, //距离画布上边的距离
          left: 125, //距离画布左侧的距离，单位是像素
          width: 1, //矩形的宽度
          height: 60, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })

        const rect2a = new fabric.Rect({
          top: 8, //距离画布上边的距离
          left: 100, //距离画布左侧的距离，单位是像素
          width: 25, //矩形的宽度
          height: 22, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })

        const rect3a = new fabric.Rect({
          top: 15, //距离画布上边的距离
          left: 100, //距离画布左侧的距离，单位是像素
          width: 25, //矩形的宽度
          height: 8, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })
        const rect4a = new fabric.Rect({
          top: 30, //距离画布上边的距离
          left: 125, //距离画布左侧的距离，单位是像素
          width: 25, //矩形的宽度
          height: 22, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })
        const rect5a = new fabric.Rect({
          top: 37, //距离画布上边的距离
          left: 125, //距离画布左侧的距离，单位是像素
          width: 25, //矩形的宽度
          height: 8, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })

        //进行组合
        var canvasObject = new fabric.Group([recta, rect1a, rect2a, rect3a, rect4a, rect5a], {
          left: left,
          top: top,
        })
        break
      case "ellipse": //椭圆00000
        var left = mouseFrom.x,
          top = mouseFrom.y
        var radius =
          Math.sqrt(
            (mouseTo.x - left) * (mouseTo.x - left) +
            (mouseTo.y - top) * (mouseTo.y - top)
          ) / 2
        canvasObject = new fabric.Circle({
          left: left,
          top: top,
          width: mouseTo.x,
          height: mouseTo.y,
          stroke: color,
          fill: "rgba(255, 255, 255, 0)",
          radius: radius,
          strokeWidth: drawWidth,
        })
        break
      case "square": //窗
        var left = mouseFrom.x,
          top = mouseFrom.y
        const rect = new fabric.Rect({
          top: 35, //距离画布上边的距离
          left: 100, //距离画布左侧的距离，单位是像素
          width: 100, //矩形的宽度
          height: 6, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
          // objectCaching: false,
        })
        const rect1 = new fabric.Rect({
          top: 30, //距离画布上边的距离
          left: 100, //距离画布左侧的距离，单位是像素
          width: 100, //矩形的宽度
          height: 16, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })
        //进行组合
        var canvasObject = new fabric.Group([rect, rect1], {
          left: left,
          top: top,
          fill: '#FFF',
          // angle: 10
        })
        break
      case "rightangle": //凸窗
        var left = mouseFrom.x,
          top = mouseFrom.y
        const rect11 = new fabric.Rect({
          top: 50, //距离画布上边的距离
          left: 16, //距离画布左侧的距离，单位是像素
          width: 100, //矩形的宽度
          height: 20, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
          // objectCaching: false,
        })
        const rect12 = new fabric.Rect({
          top: 54, //距离画布上边的距离
          left: 20, //距离画布左侧的距离，单位是像素
          width: 92, //矩形的宽度
          height: 16, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })
        const rect22 = new fabric.Rect({
          top: 58, //距离画布上边的距离
          left: 24, //距离画布左侧的距离，单位是像素
          width: 84, //矩形的宽度
          height: 16, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
        })
        //进行组合
        var canvasObject = new fabric.Group([rect11, rect12, rect22], {
          left: left,
          top: top,
          // angle: 10
        })
        break

      case "rectangle": //长方形
        var path =
          "M " +
          mouseFrom.x +
          " " +
          mouseFrom.y +
          " L " +
          mouseTo.x +
          " " +
          mouseFrom.y +
          " L " +
          mouseTo.x +
          " " +
          mouseTo.y +
          " L " +
          mouseFrom.x +
          " " +
          mouseTo.y +
          " L " +
          mouseFrom.x +
          " " +
          mouseFrom.y +
          " z"
        console.log(left, top);
        // console.log(left + 100, top);
        canvasObject = new fabric.Path(path, {
          stroke: color,
          strokeWidth: drawWidth,
          fill: "rgba(255, 255, 255, 0)",
        })

        break
      case "rectangle1": //长方形 填充
        var path =
          "M " +
          mouseFrom.x +
          " " +
          mouseFrom.y +
          " L " +
          mouseTo.x +
          " " +
          mouseFrom.y +
          " L " +
          mouseTo.x +
          " " +
          mouseTo.y +
          " L " +
          mouseFrom.x +
          " " +
          mouseTo.y +
          " L " +
          mouseFrom.x +
          " " +
          mouseFrom.y +
          " z"
        canvasObject = new fabric.Path(path, {
          left: left,
          top: top,
          stroke: "#000",
          strokeWidth: drawWidth,
          // fill: "rgba(255, 255, 255, 0)",
        })
        //也可以使用fabric.Rect
        break

      case "shuxian": //双直线
        var left = mouseFrom.x,
          top = mouseFrom.y
        var left = mouseFrom.x,
          top = mouseFrom.y
        var radius =
          Math.sqrt(
            (mouseTo.x - left) * (mouseTo.x - left) +
            (mouseTo.y - top) * (mouseTo.y - top)
          ) / 2
        // width: (left - mouseTo.x) + (top - mouseTo.y), 求宽度
        var rect0 = new fabric.Rect({
          width: (left - mouseTo.x) + (top - mouseTo.y),
          height: 16, //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小  
        });
        //进行组合
        canvasObject = new fabric.Group([rect0], {
          left: left,
          top: top,
        })
        break


      case "shuxian1": //双直线
        var left = mouseFrom.x,
          top = mouseFrom.y

        // width: (left - mouseTo.x) + (top - mouseTo.y), 求宽度
        var rect0 = new fabric.Rect({
          width: 16,
          height: (left - mouseTo.x) + (top - mouseTo.y), //矩形的高度
          fill: '', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小  
        });

        //进行组合
        canvasObject = new fabric.Group([rect0], {
          left: left,
          top: top,
        })
        break

      case "isosceles": //门
        var left = mouseFrom.x,
          top = mouseFrom.y

        const rect33 = new fabric.Rect({
          top: 99, //距离画布上边的距离
          left: 146, //距离画布左侧的距离，单位是像素
          width: 8, //矩形的宽度
          height: 50, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
          // objectCaching: false,
        })
        const rect44 = new fabric.Rect({
          top: 144, //距离画布上边的距离
          left: 154, //距离画布左侧的距离，单位是像素
          width: 10, //矩形的宽度
          height: 10, //矩形的高度
          fill: '#000', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
          // objectCaching: false,
        })
        const rect55 = new fabric.Rect({
          top: 144, //距离画布上边的距离
          left: 90, //距离画布左侧的距离，单位是像素
          width: 10, //矩形的宽度
          height: 10, //矩形的高度
          fill: '#000', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小
          // objectCaching: false,
        })
        const rect66 = new fabric.Circle({
          radius: 50,
          left: 200,
          top: 200,
          angle: 180,
          startAngle: 0,
          endAngle: Math.PI * 0.5,
          stroke: '#000',
          strokeWidth: 1,
          fill: '#FFF'
        });

        //进行组合
        canvasObject = new fabric.Group([rect33, rect44, rect55, rect66], {
          left: left,
          top: top,
          // angle: 10
        })
        break 

      case "zhijiao": //直角
        var left = mouseFrom.x,
          top = mouseFrom.y

        // var a01 = new fabric.Rect({
        //   left: 149,
        //   top: 283,
        //   width: 2,
        //   height: 18, //矩形的高度
        //   fill: '#0a0', //填充的颜色
        //   stroke: '#FFF', // 边框原色
        //   strokeWidth: 2, // 边框大小  
        // });
        // var a02 = new fabric.Rect({
        //   left: 99,
        //   top: 250,
        //   width: 18,
        //   height: 2, //矩形的高度
        //   fill: '#0a0', //填充的颜色
        //   stroke: '#FFF', // 边框原色
        //   strokeWidth: 2, // 边框大小  
        // });

        var rect00 = new fabric.Rect({
          left: 115,
          top: 285,
          width: 20,
          height: 14, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#FFF', // 边框原色
          strokeWidth: 1, // 边框大小  
        });

        var rect10 = new fabric.Rect({
          left: 100,
          top: 250,
          width: 16,
          height: 50, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小  
        });
        var rect010 = new fabric.Rect({
          left: 100,
          top: 284,
          width: 50,
          height: 16, //矩形的高度
          fill: '#FFF', //填充的颜色
          stroke: '#000', // 边框原色
          strokeWidth: 1, // 边框大小  
        });


        //进行组合
        var canvasObject = new fabric.Group([rect010, rect10, rect00], {
          left: left,
          top: top,
        })

        break

      case "text": // 写字
        textbox = new fabric.Textbox("", {
          left: mouseFrom.x - 60,
          top: mouseFrom.y - 20,
          width: 150,
          fontSize: 18,
          borderColor: "#2c2c2c",
          fill: color,
          hasControls: false,
        })
        canvas.add(textbox)
        textbox.enterEditing()
        textbox.hiddenTextarea.focus()
        break
      // 结构
      case "jiegou":
        var left = mouseFrom.x,
          top = mouseFrom.y

        const rect6a = new fabric.Line(
          [100, 420, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            // angle: 90,
            left: 100,
            top: 50,
          }
        )
        const rect7a = new fabric.Line(
          [101, 420, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            // angle: 90,
            left: 190,
            top: 50,
          }
        )
        const rect8a = new fabric.Line(
          [101, 420, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            // angle: 90,
            left: 370,
            top: 50,
          }
        )
        const rect9a = new fabric.Line(
          [101, 350, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            angle: 90,
            left: 405,
            top: 70,
          }
        )
        const rect10a = new fabric.Line(
          [101, 350, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            angle: 90,
            left: 405,
            top: 200,
          }
        )
        const rect11a = new fabric.Line(
          [101, 350, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            angle: 90,
            left: 405,
            top: 300,
          }
        )
        const rect12a = new fabric.Line(
          [101, 350, 100, 10],
          {
            stroke: "#000",
            strokeWidth: 1,
            angle: 90,
            left: 405,
            top: 430,
          }
        )

        //进行组合
        canvasObject = new fabric.Group([rect6a, rect7a, rect8a, rect9a, rect10a, rect11a, rect12a], {
          left: left,
          top: top,
        })
        // canvasObject = new fabric.Group([rect6a], {
        //   left: left,
        //   top: top,
        // })
        // canvasObject = new fabric.Group([rect7a], {
        //   left: left + 100,
        //   top: top,
        // })
        // canvasObject = new fabric.Group([rect8a], {
        //   left: left,
        //   top: top,
        // })
        // canvasObject = new fabric.Group([rect9a], {
        //   left: left,
        //   top: top,
        // })
        // canvasObject = new fabric.Group([rect10a], {
        //   left: left,
        //   top: top,
        // })
        // canvasObject = new fabric.Group([rect11a], {
        //   left: left,
        //   top: top,
        // })
        // canvasObject = new fabric.Group([rect12a], {
        //   left: left,
        //   top: top,
        // })

        break


      case "remove":

        break
      case "remove1":
        break
      default:
        break
    }
    if (canvasObject) {
      // canvasObject.index = getCanvasObjectIndex();
      canvas.add(canvasObject) //.setActiveObject(canvasObject)
      drawingObject = canvasObject
    }
    replayllist.push(canvas.toJSON())
  }

  // canvas.on("selection:created",function (e) {
  //   if (e.target._objects) {
  //     canvas.remove(e.target);
  //     // console.log(e.target._objects,"删除");
  //     //多选删除
  //     var etCount = e.target._objects.length;
  //     for (var etindex = 0;etindex < etCount;etindex++) {
  //       canvas.remove(e.target._objects[etindex]);
  //     }1
  //   } else {
  //     //单选删除
  //     canvas.remove(e.target);
  //   }
  //   canvas.discardActiveObject(); //清楚选中框
  // });


  var remove = document.getElementById("remove");
  remove.onclick = function (e) {
    
    canvas.getActiveObject().remove() //清楚选中框
    console.log("进来了?");
  }



  // function arrr() {
  //   canvas.discardActiveObject(); //清楚选中框
  // };

  //绘制箭头方法
  function drawArrow(fromX, fromY, toX, toY, theta, headlen) {
    theta = typeof theta != "undefined" ? theta : 30
    headlen = typeof theta != "undefined" ? headlen : 10
    // 计算各角度和对应的P2,P3坐标
    var angle = (Math.atan2(fromY - toY, fromX - toX) * 180) / Math.PI,
      angle1 = ((angle + theta) * Math.PI) / 180,
      angle2 = ((angle - theta) * Math.PI) / 180,
      topX = headlen * Math.cos(angle1),
      topY = headlen * Math.sin(angle1),
      botX = headlen * Math.cos(angle2),
      botY = headlen * Math.sin(angle2)
    var arrowX = fromX - topX,
      arrowY = fromY - topY
    var path = " M " + fromX + " " + fromY
    path += " L " + toX + " " + toY
    arrowX = toX + topX
    arrowY = toY + topY
    path += " M " + arrowX + " " + arrowY
    path += " L " + toX + " " + toY
    arrowX = toX + botX
    arrowY = toY + botY
    path += " L " + arrowX + " " + arrowY
    return path
  }

  //获取画板对象的下标
  function getCanvasObjectIndex() {
    return canvasObjectIndex++
  }
  //保存历史轨迹
  function updateModifications(savehistory) {
    if (savehistory == true) {
      fabricHistoryJson.push(JSON.stringify(canvas))
    }
  }
  //后退
  function undo() {
    let state = fabricHistoryJson
    if (mods < state.length) {
      canvas.clear().renderAll()
      canvas.loadFromJSON(state[state.length - 1 - mods - 1])
      canvas.renderAll()
      mods += 1
    }
  }
  //前进
  function redo() {
    let state = fabricHistoryJson
    if (mods > 0) {
      canvas.clear().renderAll()
      canvas.loadFromJSON(state[state.length - 1 - mods + 1])
      canvas.renderAll()
      mods -= 1
    }
  }
})()



// //保存 透明图片
// function draw() {
//   var ctx = document.getElementById('c').getContext('2d');
//   var img = new Image();
//   img.onload = function () {
//     ctx.drawImage(img, 0, 0);
//     ctx.beginPath();
//     ctx.stroke();
//   }
//   img.src = 'btnNews.png';
// }
// draw();

// // var canvas = document.getElementById('c');
// //绑定下载事件
// var baocun = document.getElementById("baocun");
// baocun.onclick = function () {
//   console.log("进来了?");
//   var type = 'png';
//   download(type);
// }
// //图片下载操作,指定图片类型
// function download(type) {
//   //设置保存图片的类型
//   var imgdata = canvas.toDataURL(type);
//   document.getElementById('down').href = imgdata;
//   console.log(imgdata)
//   //将mime-type改为image/octet-stream,强制让浏览器下载
//   var fixtype = function (type) {
//     type = type.toLocaleLowerCase().replace(/jpg/i, 'jpeg');
//     var r = type.match(/png|jpeg|bmp|gif/)[0];
//     return 'image/' + r;
//   }
//   imgdata = imgdata.replace(fixtype(type), 'image/octet-stream')
//   //将图片保存到本地
//   var saveFile = function (data, filename) {
//     var link = document.createElement('a');
//     link.href = data;
//     link.download = filename;
//     var event = document.createEvent('MouseEvents');
//     event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
//     link.dispatchEvent(event);
//   }
//   var filename = new Date().toLocaleDateString() + '.' + type;
//   saveFile(imgdata, filename);
// }


var baocun = document.getElementById("baocun");
// 保存
baocun.onclick = function () {
  console.log("进来了?s");

  downloadFile('ship.png', canvas.toDataURL("image/png"));
}
function base64Img2Blob(code) {
	// console.log(code);
  var parts = code.split(';base64,');
  var contentType = parts[0].split(':')[1];
  var raw = window.atob(parts[1]);
  var rawLength = raw.length;

  var uInt8Array = new Uint8Array(rawLength);

  for (var i = 0;i < rawLength;++i) {
    uInt8Array[i] = raw.charCodeAt(i);
  }

  return new Blob([uInt8Array], { type: contentType });
}
function downloadFile(fileName, content) {

  var aLink = document.createElement('a');
  var blob = base64Img2Blob(content); //new Blob([content]);


  var evt = document.createEvent("MouseEvents");
  evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错
  //aLink.download = fileName;
  //网络图片
  // aLink.href = "https://www.sage.run/imgs/avater.jpg"
  //aLink.href = URL.createObjectURL(blob);

  aLink.dispatchEvent(evt);
  var bitmap = new window.plus.nativeObj.Bitmap('image');
  console.log(content);
  bitmap.loadBase64Data(content,function(i){
	  bigmapToSave(bitmap)
  },function(err){
	 console.log(JSON.stringify(err));
  })
}
function bigmapToSave(bitmap){
	var name = randomString(8);
	console.log('-----------------------------'+JSON.stringify(bitmap));
	bitmap.save(`_doc/${name}.png`,{overwrite:false},function(event){
		console.log(event.target);
		imageSaveByGallery(event.target);
	},
	function(err){
		console.log(err);
	})
}
function imageSaveByGallery(url){
	window.plus.gallery.save(url,function(event){
		var tarbitmap = window.plus.nativeObj.Bitmap.getBitmapById('image');
		
		tarbitmap.clear();
		console.log('成功');
		alert('保存成功!');
		plus.nativeUI.actionSheet( {title:"保存成功!",cancel:"确认"}, function(e){
		console.log( "User pressed: "+e.index );
		} );
		
	},function(err){
		console.log('失败');

	})
}
function randomString(e){
	e = e||32
	var t ='QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm123456798';
	var a=t.length;
	var n='';
	for(var i =0;i<e;i++){
		n+=t.charAt(Math.floor(Math.random()*a));
	}
	return n;
}

//000000000000000000000000000000000000000000000000000000000000000000000000000

// function imageDown(base64, success, error) {

//   var bitmap = new window.plus.nativeObj.Bitmap('image')

//   bitmap.loadBase64Data(base64, function (i) {

//     bigmapToSave(bitmap, success, error)

//   }, function (err) {

//     window.plus.nativeUI(err.message)

//   })

// }

// function bigmapToSave(bitmap, success, error) {

//   var name = randomString(10)

//   bitmap.save(`_doc/${name}.jpg`, { overwrite: false }, function (event) {

//     console.log(event.target)

//     imageSaveByGallery(event.target, success, error)

//   }, function (err) {

//     window.plus.nativeUI(err.message)

//   })

// }

// function imageSaveByGallery(url, success, error) {

//   window.plus.gallery.save(url, function (event) {

//     const tarbitmap = window.plus.nativeObj.Bitmap.getBitmapById('image')

//     tarbitmap.clear()

//     success()

//   }, function (err) {

//     window.plus.nativeUI(err.message)

//     error()

//   })

// }

// const randomString = function randomString(e) {

//   e = e || 32

//   var t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'

//   var a = t.length

//   var n = ''

//   for (var i = 0;i < e;i++) n += t.charAt(Math.floor(Math.random() * a))

//   return n

// }


function downloadIamgeMUI(urls) {
  console.log(urls,444444444444);
  let that = this;

  mui.plusReady(() => {
    console.log("进来了111111");
    // 创建下载任务 图片下载地址
    var picurl = urls
    console.log(picurl,"00000000");
    // var picurl = 'http://47.111.120.123/userfiles/程序附件/wx/20190725110730327554.png';
    //图片保存到手机后的路径
    var dtask = plus.downloader.createDownload(picurl, {}, function (d, status) {
      // 下载完成

      console.log(status);
      if (status == 200) {
        plus.gallery.save(d.filename, function () { //保存到相册方法
          that.$toast('图片已保存本地。')

        }, function () {
          that.$toast('图片已保存失败。')
        });
      } else {
        that.$toast('图片已保存失败。')
      }
    })
    dtask.start() //开始下载
  })

}